package com.jiajia.study;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: DelayApplication
 * @Author zjj
 * @Package com.jiajia.study
 * @Date 2024/3/11 11:12
 * @description:
 */

@SpringBootApplication
@Slf4j
public class DelayApplication implements ApplicationRunner {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DelayApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Thread.sleep(3000L);
//        displayDelay();
        displayDelayPlugin();
    }

    private void displayDelayPlugin() throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            Thread.sleep(1000);
            MessageProperties messageProperties = new MessageProperties();
            Map<String,Object> map = new HashMap<>();
            // 延迟时间为 10 秒钟
            map.put("x-delay",10*1000);
            messageProperties.setHeaders(map);
            Message message = new Message(("test delay v2" + i).getBytes(StandardCharsets.UTF_8),messageProperties);
            rabbitTemplate.convertAndSend("exchange.delay.v2","delayv2",message);
            log.info("send message success : {}",new Date());
        }
    }

    private void displayDelay() {
        rabbitTemplate.convertAndSend("delay.exchange.normal","normal","test delay".getBytes(StandardCharsets.UTF_8));
    }
}
